package codetop.microsoft.T166;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 18362
 * @Create: 2022-09-08 0:52:36 星期四
 */
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0)
            return "0";
        boolean flag = false;
        long num = numerator, den = denominator;
        if ((num < 0 && den < 0) || (num > 0 && den > 0))
            flag = true;
        num = num < 0 ? -num : num;
        den = den < 0 ? -den : den;
        long base = num / den;
        num %= den;
        if (num == 0)
            return flag ? String.valueOf(base) : "-" + String.valueOf(base);
        num *= 10;
        List<String> res = new ArrayList<>();
        int end = -1;
        String dup = "";
        Map<Long, Integer> map = new HashMap<>();
        while (num > 0) {
            while (num < den) {
                res.add("0");
                map.put(num, res.size() - 1);
                num *= 10;
            }
            res.add(String.valueOf(num / den));
            map.put(num, res.size() - 1);
            num %= den;
            num *= 10;
            if (map.containsKey(num)) {
                end = map.get(num);
                StringBuilder sb = new StringBuilder();
                for (int i = end; i < res.size(); ++i)
                    sb.append(res.get(i));
                dup = "(" + sb.toString() + ")";
                break;
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append(base).append(".");
        if (end < 0) {
            for (int i = 0; i < res.size(); ++i)
                sb.append(res.get(i));
        } else {
            for (int i = 0; i < end; ++i)
                sb.append(res.get(i));
            sb.append(dup);
        }
        return flag ? sb.toString() : "-" + sb.toString();
    }
}